<?php
namespace App\Services\Rating;

use Illuminate\Support\Facades\DB;
use App\Models\System\Term;
use App\Models\System\Scale;
use App\Models\System\ScaleDetail;
use App\Models\System\Tasks;
use App\Models\System\Rolepower;
use App\Models\BasicTitleInfo;
use App\Models\Teachers;
use App\Models\BasicInfoGraduatedSchool;
use App\Models\Teaching\TeachingSubject;
use App\Models\Rating\Job;
use App\Models\Rating\JobApply;
use App\Models\Rating\JobApplyDetails;
use App\Models\Rating\JobApplyScores;
use App\Models\Rating\JobApplyChecks;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Excel\ExcelExport;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class JobService{

    /**
     * 列表
     * @author lxy
     * @datetime 2023-03-08
     */
    public function getJobList($request)
    {
        $limit = $request['limit'] ?? 10;
        $where = [];

        $user_id = auth()->user()->id;
        $role_id = auth()->user()->cur_role_id;
 
        !empty($request['search']['data_version_id'])   && $where[] = ['jobs.data_version_id','=',$request['search']['data_version_id']];
        !empty($request['search']['author_name'])     && $where[] = ['jobs.author_name','like','%'.$request['search']['author_name'].'%'];
        !empty($request['search']['name'])     && $where[] = ['jobs.name','like','%'.$request['search']['name'].'%'];
        !empty($request['search']['level'])     && $where[] = ['jobs.level_text','like','%'.$request['search']['level'].'%'];
        if(isset($request['search']['status']) &&  $request['search']['status'] === '0'){
            $where[] = ['jobs.status','=',$request['search']['status']];
        }else if(isset($request['search']['status']) &&  $request['search']['status'] == 1){
            $where[] = ['jobs.status','=',1];
            $where[] = ['jobs.submit_start','>',date('Y-m-d H:i:s')];
        }else if(isset($request['search']['status']) &&  $request['search']['status'] == 2){
            $where[] = ['jobs.status','=',1];
            $where[] = ['jobs.submit_start','<=',date('Y-m-d H:i:s')];
            $where[] = ['jobs.submit_end','>=',date('Y-m-d H:i:s')];
        }else if(isset($request['search']['status']) &&  $request['search']['status'] == 3){
            $where[] = ['jobs.status','=',1];
            $where[] = ['jobs.submit_end','>',date('Y-m-d H:i:s')];
        }

        if(!empty($request['search']['date'])){
            $date = explode(' - ',$request['search']['date']);
            $where[] = ['jobs.check_start','>=',$date[0]];
            $where[] = ['jobs.check_end','<=',$date[1]];
        }

        //获取当前用户的岗位等级 与岗位聘任日期
      
        $title_info = BasicTitleInfo::where('user_id',$user_id)->where('deleted',0)->first();
        $u_level = ''; //岗位级别
        $u_level_date = ''; //岗位级别聘任日期
        if($title_info){
            $title_info = $title_info->toArray();
            $u_level = $title_info['rank_set'][0]['selectKey'];
            $u_level_date = $title_info['tea_gain_time'];
        }
        //dd($u_level,$u_level_date);
        //非管理员只能看到符合自身申报条件的任务
        $whereStr = '';
        if(!is_checker()){
            $whereStr = "(user_id='{$user_id}') or (jobs.leader like '%{$user_id}%' or jobs.members like '%{$user_id}%' ) ";

            if($u_level && $u_level_date){
                $s_level = $u_level-1;
                if(!in_array($s_level,[4,7,13,10])){
                    $u_data = date('Y-m-d H:i:s',strtotime("+3 year", strtotime($u_level_date)));
                    $whereStr .= "or (jobs.status=1 and jobs.submit_start > '{$u_data}' and jobs.level like '%{$s_level}%' )";
                 }
            }

            // if(!$u_level && !$u_level_date){
            //     return ['data'=>[]];
            // }
            // $s_level = $u_level-1;
            // //跨级别岗位等级不能申报 比如：教师级别是6级的，可以申报为5级
            // if(in_array($s_level,[4,7,13,10])){
            //     return ['data'=>[]];
            // }
        
            //$u_data = date('Y-m-d H:i:s',strtotime("+3 year", strtotime($u_level_date)));
           // $where[] = [DB::raw(" ( (user_id='{$user_id}') or (jobs.status=1 and jobs.submit_end > '{$u_data}' and jobs.level like '%".'"'.$s_level.'"'."%' ) or (jobs.leader like '%".'"'.$user_id.'"'."%' or jobs.members like '%".'"'.$user_id.'"'."%' ) ) "),1];
           $where[] = [DB::raw(" ( $whereStr ) "),1];
        }          

        $rolepower = Rolepower::where('role_id',$role_id)->pluck('actionid')->toArray();
        //dd($where);
        $result = Job::where($where)
                    ->select('jobs.*','b.status as b_status')
                    ->leftJoin('job_apply as b','jobs.id','=','b.job_id')
                    ->orderBy('created_at','desc')
                    ->paginate($limit)
                    ->toArray();
                    
        foreach($result['data'] as $k=>&$v){
            if(!$u_level && !$u_level_date){
                $v['is_apply'] = 0; //是否能够查看和申请 1-是 0-否
            }else{
                //dd($u_level,$v['level_array'],$u_level_date);
                $v['is_apply'] = $this->level_filter($u_level,$v['level_array'],$u_level_date,$v['submit_start']);
            }
            if($v['b_status'] === null){
                $v['apply_text'] = '未申报';
            }else if($v['b_status'] == 0){
                $v['apply_text'] = '待提交';
            }else if($v['b_status'] == 1){
                $v['apply_text'] = '已申报';
            }

            if( in_array('201',$rolepower) || (!empty($v['leader_array']) && in_array($user_id,$v['leader_array']['value'])) || (!empty($v['members_array']) && in_array($user_id,$v['members_array']['value'])) ){
                $v['is_check'] = 1; //可以审核
            }else{
                $v['is_check'] = 0; //不能审核
            } 
        }
        
        $result['limit'] = $limit;
        return $result;
    }

    /**
     * @Description: 导出
     * @Author: lxy
     * @datetime: 2023-03-30
     */
    public function exportJob($request)
    {
        $where = [];

        $user_id = auth()->user()->id;
        $role_id = auth()->user()->cur_role_id;
 
        !empty($request['search']['data_version_id'])   && $where[] = ['jobs.data_version_id','=',$request['search']['data_version_id']];
        !empty($request['search']['author_name'])     && $where[] = ['jobs.author_name','like','%'.$request['search']['author_name'].'%'];
        !empty($request['search']['name'])     && $where[] = ['jobs.name','like','%'.$request['search']['name'].'%'];
        !empty($request['search']['level'])     && $where[] = ['jobs.level_text','like','%'.$request['search']['level'].'%'];
        if(isset($request['search']['status']) &&  $request['search']['status'] === '0'){
            $where[] = ['jobs.status','=',$request['search']['status']];
        }else if(isset($request['search']['status']) &&  $request['search']['status'] == 1){
            $where[] = ['jobs.status','=',1];
            $where[] = ['jobs.submit_start','>',date('Y-m-d H:i:s')];
        }else if(isset($request['search']['status']) &&  $request['search']['status'] == 2){
            $where[] = ['jobs.status','=',1];
            $where[] = ['jobs.submit_start','<=',date('Y-m-d H:i:s')];
            $where[] = ['jobs.submit_end','>=',date('Y-m-d H:i:s')];
        }else if(isset($request['search']['status']) &&  $request['search']['status'] == 3){
            $where[] = ['jobs.status','=',1];
            $where[] = ['jobs.submit_end','>',date('Y-m-d H:i:s')];
        }

        if(!empty($request['search']['date'])){
            $date = explode(' - ',$request['search']['date']);
            $where[] = ['jobs.check_start','>=',$date[0]];
            $where[] = ['jobs.check_end','<=',$date[1]];
        }

        //获取当前用户的岗位等级 与岗位聘任日期
      
        $title_info = BasicTitleInfo::where('user_id',$user_id)->where('deleted',0)->first();
        $u_level = ''; //岗位级别
        $u_level_date = ''; //岗位级别聘任日期
        if($title_info){
            $title_info = $title_info->toArray();
            $u_level = $title_info['rank_set'][0]['selectKey'];
            $u_level_date = $title_info['tea_gain_time'];
        }
    
        //非管理员只能看到符合自身申报条件的任务
        $whereStr = '';
        if(!is_checker()){
            $whereStr = "(user_id='{$user_id}') or (jobs.leader like '%{$user_id}%' or jobs.members like '%{$user_id}%' ) ";

            if($u_level && $u_level_date){
                $s_level = $u_level-1;
                if(!in_array($s_level,[4,7,13,10])){
                    $u_data = date('Y-m-d H:i:s',strtotime("+3 year", strtotime($u_level_date)));
                    $whereStr .= "or (jobs.status=1 and jobs.submit_start > '{$u_data}' and jobs.level like '%{$s_level}%' )";
                 }
            }

            // if(!$u_level && !$u_level_date){
            //     return ['data'=>[]];
            // }
            // $s_level = $u_level-1;
            // //跨级别岗位等级不能申报 比如：教师级别是6级的，可以申报为5级
            // if(in_array($s_level,[4,7,13,10])){
            //     return ['data'=>[]];
            // }
        
            //$u_data = date('Y-m-d H:i:s',strtotime("+3 year", strtotime($u_level_date)));
           // $where[] = [DB::raw(" ( (user_id='{$user_id}') or (jobs.status=1 and jobs.submit_end > '{$u_data}' and jobs.level like '%".'"'.$s_level.'"'."%' ) or (jobs.leader like '%".'"'.$user_id.'"'."%' or jobs.members like '%".'"'.$user_id.'"'."%' ) ) "),1];
           $where[] = [DB::raw(" ( $whereStr ) "),1];
        }          

        $rolepower = Rolepower::where('role_id',$role_id)->pluck('actionid')->toArray();
        //dd($where);
        $result = Job::where($where)
                    ->select('jobs.*','b.status as b_status')
                    ->leftJoin('job_apply as b','jobs.id','=','b.job_id')
                    ->orderBy('created_at','desc')
                    ->get()
                    ->toArray();
                    
        foreach($result as $k=>&$v){
            if(!$u_level && !$u_level_date){
                $v['is_apply'] = 0; //是否能够查看和申请 1-是 0-否
            }else{
                //dd($u_level,$v['level_array'],$u_level_date);
                $v['is_apply'] = $this->level_filter($u_level,$v['level_array'],$u_level_date,$v['submit_start']);
            }
            if($v['b_status'] === null){
                $v['apply_text'] = '未申报';
            }else if($v['b_status'] == 0){
                $v['apply_text'] = '待提交';
            }else if($v['b_status'] == 1){
                $v['apply_text'] = '已申报';
            }

            if( in_array('201',$rolepower) || (!empty($v['leader_array']) && in_array($user_id,$v['leader_array']['value'])) || (!empty($v['members_array']) && in_array($user_id,$v['members_array']['value'])) ){
                $v['is_check'] = 1; //可以审核
            }else{
                $v['is_check'] = 0; //不能审核
            } 
        }
        
         
        if(!is_checker()){
            $field_name = ['学年学期','名称','考核起止时间','申报起止时间','状态','申报状态']; 
        }else{
            $field_name = ['学年学期','名称','岗位级别','岗位空缺数量','考核起止时间','状态','创建人','创建时间']; 
        }
        $data = [];
        foreach($result as $k=>$v){
            if(!is_checker()){
                $data[$k][] = $v['data_version_name'] === null?'':$v['data_version_name'];
                $data[$k][] = $v['name'];
                $data[$k][] = ($v['check_start'] !== null && $v['check_end'] !== null)?$v['check_start'].' - '.$v['check_end']:'';
                $data[$k][] = ($v['submit_start'] !== null && $v['submit_end'] !== null)?$v['submit_start'].' - '.$v['submit_end']:'';
                $data[$k][] = $v['submit_text'];
                $data[$k][] = $v['apply_text'];
            }else{
                $data[$k][] = $v['data_version_name'] === null?'':$v['data_version_name'];
                $data[$k][] = $v['name'];
                $data[$k][] = $v['level_text'];
                $data[$k][] = $v['sum'];
                $data[$k][] = ($v['check_start'] !== null && $v['check_end'] !== null)?$v['check_start'].' - '.$v['check_end']:'';
                $data[$k][] = $v['submit_text'];
                $data[$k][] = $v['author_name'];
                $data[$k][] = $v['created_at'];
            }                  
        }
        array_unshift($data,$field_name);
        
        $file_name = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($data), $file_name, 'excel');
        return [
            'file_name' => $file_name,
        ];
    }

    /**
     * 是否满足申报条件
     * @author lxy
     * @datetiem 2023-03-09
     * @param $level int 当前岗位级别
     * @param $levels array 申报的岗位级别
     * @param $level_date date 岗位聘任日期
     * @param $submit_start date 申报开始日期
     * @return int 1-是 0-否
     */
    private function level_filter($level,$levels,$level_date,$submit_start)
    {   
        foreach($levels as $k=>$v){
            if(in_array($v,[4,7,13,10])){
                unset($levels[$k]);
            }else{
                $levels[$k] = ++$v;
            }
        } 
        $levels = array_values($levels);
        //聘任日期满三年
        $level_date_3 = strtotime("+3 year", strtotime($level_date));
        //岗位级别满足并且聘任时间大于3年
        //dd($level_date,$submit_start,$level_date_3,date('Y-m-d H:i:s',$level_date_3));
        if(in_array($level,$levels) && strtotime($submit_start)>$level_date_3){
            return 1;
        }
        return 0;
    }

    /**
     * 添加
     * @author lxy
     * @datetime 2023-03-08
     */
    public function addJob($request)
    {
        $id = !empty($request['id'])?$request['id']:0;
        //学期名称
        $data_versions = Term::where('id',$request['data_version_id'])->first()->toArray();

        !empty($request['level']) && $request['level'] = json_encode($request['level']);
        !empty($request['materials_date']) && $request['materials_date'] = json_encode($request['materials_date']);
        !empty($request['leader']) && $request['leader'] = json_encode($request['leader']);
        !empty($request['members']) && $request['members'] = json_encode($request['members']);
   
        if(!empty($request['files'])){
            $files = json_decode($request['files'],true);
            foreach($files as $k=>$v){
                if(empty($v)) unset($files[$k]);
            }
            $files = array_values($files);
            $request['files']  = json_encode($files);
        }else{
            unset($request['files']);
        }     
        unset($request['id'],$request['file']);
        if(empty($request['check_start'])) unset($request['check_start']);
        if(empty($request['check_end'])) unset($request['check_end']);
        if(empty($request['submit_start'])) unset($request['submit_start']);
        if(empty($request['submit_end'])) unset($request['submit_end']);
        
        //已经提交过的数据不能保存
        if($request['status'] == '0'){
            if($id){
                $status = Job::where('id',$id)->value('status');
                if($status == '1'){
                    throw new \Exception('已提交过的数据不能继续保存');
                }
            }        
        }

        //考评组长考评成员去重
        if(!empty($request['leader']) && !empty($request['members'])){
            $request['leader'] = json_decode($request['leader'],true);
            $request['members'] = json_decode($request['members'],true);
            foreach($request['leader'] as $k=>$v){
                foreach($request['members'] as $k2=>$v2){
                    if($v['value'] == $v2['value']){
                        unset($request['members'][$k2]);
                    }
                }
            }
            if(empty($request['members'])){
                throw new \Exception('考评组长和考评成员不能重复');
            }
            $request['leader'] = json_encode($request['leader']);
            $request['members'] = json_encode(array_values($request['members']));
        }
        
        if(!$id){ 
            //新增
            $request['data_version_name'] = $data_versions['title'];
            $request['author_id'] = auth()->user()->id;
            $request['author_name'] = auth()->user()->nickname;
            $result = Job::create($request);
            return $result->id;
        }else{
            //编辑
            $request['data_version_name'] = $data_versions['title'];
            $result = Job::where('id',$id)->update($request);
            return $result;
        }
       
    }

    /**
     * 获取一条数据
     * @author lxy
     * @datetime 2023-03-09
     */
    public function getJobFirst($request)
    {
        $id = $request['id'];
        $result = Job::where('id',$id)->first();
        if(!$result){
            return [];
        }
        return $result->toArray();
    }

    /**
     * 删除
     * @author lxy
     * @datetime 2023-03-09
     */
    public function delJob($request)
    {
        $id = $request['id'];
        $result = Job::where('id',$id)->delete();
        return $result;
    }

    /**
     * 选择量表
     * @author lxy
     * @datetime 2023-03-10
     */
    public function getJobScale($request)
    {
        return Scale::select('id','name')->where('type',1)->get()->toArray();
    }

    /**
     * 获取发展性项目
     * @author lxy
     * @datetime 2023-03-10
     */
    public function getJobScaleList($request)
    {
        $scale_index = $request['scale_index'];
        $scale_id = $request['scale_id'];
        $job_apply_id = $request['job_apply_id'];
        if($scale_index == 2){
            //科教研 特殊处理
            $result = ScaleDetail::whereIn('scale_index',[2,3])->where('is_end',1)->where('scale_id',$scale_id)
                ->with(['jobApplyDetails'=>function($q) use($job_apply_id){
                    $q->where('job_apply_id',$job_apply_id)->where('type',2);
                }])->get()->toArray();
             //dd( $result);
            $data = [];
            foreach($result as $k=>$v){
                $data[$v['scale_index']][] = $v;
            }
            return $data;
        }else if($scale_index == 5){
            //公开教学，特殊处理
            $result = ScaleDetail::whereIn('scale_index',[5,10])->where('is_end',1)->where('scale_id',$scale_id)
                ->with(['jobApplyDetails'=>function($q) use($job_apply_id){
                    $q->where('job_apply_id',$job_apply_id)->where('type',2);
                }])->get()->toArray();
             
            $data = [];
            foreach($result as $k=>$v){
                $data[$v['scale_index']][] = $v;
            }
            return $data;
        }else{
            $result = ScaleDetail::where('scale_index',$scale_index)->where('is_end',1)->where('scale_id',$scale_id)
            ->with(['jobApplyDetails'=>function($q) use($job_apply_id){
                $q->where('job_apply_id',$job_apply_id)->where('type',2);
            }])->get()->toArray();
        }
        
        return $result;
    }

    /**
     * 获取岗位竞聘信息
     * @author lxy
     * @datetime 2023-03-13
     */
    public function getJobApplyFirst($request)
    {   
        if(!empty($request['user_id'])){
            $user_id = $request['user_id'];
        }else{
            $user_id = auth()->user()->id;
        }
 
        $job_id = $request['job_id'];
        $result = JobApply::where([['job_id','=',$job_id],['user_id','=',$user_id]])->with(['job_apply_details'=>function($q) {
                    $q->where('type',1);
                },'job_apply_check'=>function($q){
                    $q->where('status',1);
                }])->first();
       
        if(!$result){
            $title_info = BasicTitleInfo::where('user_id',$user_id)->where('deleted',0)->first();
            if(!$title_info){
                throw new \Exception('基础数据缺失，无法申报或查看');
            }
            if(empty($title_info['rank_set']) || !$title_info['tea_gain_time']){
                throw new \Exception('缺少原岗位等级或教师职称获得日期,无法申报或查看');
            }
            $title_info = $title_info->toArray();
            $job =  Job::where('id',$job_id)->first()->toArray();
            $teachers = Teachers::where('user_id',$user_id)->where('deleted',0)->first();
            $teaching_subject = TeachingSubject::where('data_version_id',$job['data_version_id'])->where('user_id',$user_id)->where('deleted',0)->first();
            $big_School = BasicInfoGraduatedSchool::where('user_id',$user_id)->where('deleted',0)->first();

            $data = [
                'job_id'=>$job_id,
                'data_version_id'=>$job['data_version_id'],
                'data_version_name'=>$job['data_version_name'],
                'name'=>auth()->user()->nickname,            
                'join_job_date'=>$teachers?$teachers->work_date:'',
                'old_level'=>$title_info['rank_set'][0]['selectKey'],
                'old_level_name'=>$title_info['rank_set'][0]['selectValue'],
                'engage_date'=>$title_info['tea_employ_time']?$title_info['tea_employ_time']:[],
                'apply_level'=>$title_info['rank_set'][0]['selectKey']-1,
                'apply_level_name'=>$this->level($title_info['rank_set'][0]['selectKey']-1),
                'subject'=>$teaching_subject?implode(',',array_column($teaching_subject->toArray()['subject_set'],'selectValue')):'',
                'user_id'=>$user_id,
                'education'=>!empty($big_School['academic_set'])?$big_School['academic_set'][0]['selectKey']:'',
                'education_name'=>!empty($big_School['academic_set'])?$big_School['academic_set'][0]['selectValue']:'',
                'teaching_age'=>$teachers?$teachers->teaching_year:'',
                'engage_age'=>$title_info?$title_info['employ_year']:'',
                'remark'=>'',
                'training'=>'',
                'zf'=> 0, //总分
                'job_apply_details' =>[
                    '1' => ['comment'=>'','scores'=>!empty($big_School['academic_set'])?$this->education($big_School['academic_set'][0]['selectKey']):0], 
                    '2' => ['comment'=>'','scores'=>0],
                    '3' => ['comment'=>'','scores'=>($teachers && $teachers->teaching_year)?$this->teaching_age($teachers->teaching_year):0],
                    '4' => ['comment'=>'','scores'=>$title_info?$title_info['employ_year']:0],
                ]
            ];

            //JobApply::create($data);
            return $data;
        }
        $result = $result->toArray();

        $zs = !empty($result['job_apply_check'])?array_sum(array_column($result['job_apply_check'],'scores')):0;
        $check_sum = !empty($result['job_apply_check'])?count($result['job_apply_check']):0;
        $result['zf'] = $zs?round($zs/$check_sum,1):0;     

        $result['job_apply_details'] = array_column($result['job_apply_details'],null,'scale_id');
        return $result;

    }

    /**
     * 提交申报
     * @author lxy
     * @datetime 2023-03-15
     */
    public function addApply($request)
    {      
        $data = $request['form'];
        $id = $data['id'];
        unset($data['id']);

        $user = auth()->user();
        $data['status'] = $request['status'];
        $data['training'] = $request['training'];
        $data['remark'] = !empty($request['remark'])?$request['remark']:'';
  
        try{
            DB::beginTransaction();
            if(!$id){
                $jobApply = JobApply::create($data);
                $data2= [];
                foreach($request['comment'] as $k=>$v){
                    $data2[$k]['job_apply_id'] = $jobApply->id;
                    $data2[$k]['scale_id'] = $k;
                    $data2[$k]['comment'] = $v;
                }
                foreach($request['scores'] as $k=>$v){
                    $data2[$k]['scores'] = $v;
                }
                $data2 = array_values($data2);
                JobApplyDetails::insert($data2);
                $id = $jobApply->id;              
            }else{
                JobApply::where('id',$id)->update(['remark'=>$data['remark'],'status'=>$data['status'],'training'=>$data['training']]);
                $data2= [];
                foreach($request['comment'] as $k=>$v){
                    $data2[$k]['scale_id'] = $k;
                    $data2[$k]['comment'] = $v;
                }
                foreach($request['scores'] as $k=>$v){
                    $data2[$k]['scores'] = $v;
                }  
                       
                foreach($data2 as $k=>$v){
                    JobApplyDetails::where([
                        ['job_apply_id','=',$id],
                        ['scale_id','=',$v['scale_id']],
                        ['type','=',1],
                    ])->update(['comment'=>$v['comment'],'scores'=>$v['scores']]);
                }
                              
            } 

            //申报提交之后给所有小组评分成员发生代办事项
            if($request['status'] == 1 && !Tasks::where('form_key','TEACHER_TASKS')->where('form_id',$id)->where('status',1)->first()){
                $job = Job::where('id',$request['form']['job_id'])->first()->toArray();
                $members = array_merge($job['leader_array']['all'],$job['members_array']['all']);
       
                $data = [];
                foreach($members as $k=>$v){
                    $data[$k]['name']='【'.$request['form']['data_version_name'].'】考核管理-岗位竞聘审核';
                    $data[$k]['data_version_id']=$request['form']['data_version_id'];
                    $data[$k]['form_id']=$id;
                    $data[$k]['form_key']='TEACHER_TASKS';
                    $data[$k]['start_date']=date('Y-m-d H:i:s');
                    $data[$k]['end_date']=$job['check_end'];
                    $data[$k]['c_user_id']=$v['value'];
                    $data[$k]['c_user_name']=$v['name'];
                    $data[$k]['type']=2;
                    $data[$k]['creator_id']=$user->id;
                    $data[$k]['creator_name']=$user->nickname;
                    $data[$k]['param']='?job_id='.$job['id'].'&scale_id='.$job['scale_id'].'&user_id='.$user->id.'&job_apply_id='.$request['form']['id'];
                    $data[$k]['url']='/rating/job/check';
                    $data[$k]['menu_id']=299;
                    $data[$k]['created_at']=date('Y-m-d H:i:s');
                    $data[$k]['updated_at']=date('Y-m-d H:i:s');
                }
                Tasks::insert($data);
            } 
            DB::commit(); 
            return $id;             
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 添加发展性项目
     * @author lxy
     * @datetime 2023-03-16
     */
    public function addFzxxm($request)
    {
        $modules = array_column($request['data'],'id');
      
        foreach($modules as $k=>$v){
            $a = JobApplyDetails::where([
                ['job_apply_id','=',$request['job_apply_id']],
                ['scale_index','=',$request['scale']['scale_index']],
                ['type','=',2],
                ['modules','like','%"'.$v.'"%'],
            ])->first();
            if($a){
                throw new \Exception('数据存在重复');    
            }
        }
     
        $jobApplyDetails = JobApplyDetails::where([
            ['job_apply_id','=',$request['job_apply_id']],
            ['scale_id','=',$request['scale']['id']],
            ['type','=',2],
        ])->first();
        
        if($jobApplyDetails){
            //更新
            if(!empty($jobApplyDetails->modules)){
                $data = ['modules'=>json_encode(array_merge(json_decode($jobApplyDetails->modules,true) ,$modules))];
            }else{
                $data = ['modules'=>json_encode($modules)];
            }
            JobApplyDetails::where([
                ['job_apply_id','=',$request['job_apply_id']],
                ['scale_id','=',$request['scale']['id']],
                ['type','=',2],
            ])->update($data);
            return $jobApplyDetails->id;
        }else{
            //添加
            $data['job_apply_id'] = $request['job_apply_id'];
            $data['scale_id'] = $request['scale']['id'];
            $data['scale_index'] = $request['scale']['scale_index'];
            $data['modules'] = json_encode($modules);
            $data['modules_id'] = $request['scale']['module'];
            $data['type'] = 2;
            $result = JobApplyDetails::create($data);
            return $result->id;
        }   
    }

    /**
     * 删除发展性项目
     * @author lxy
     * @datetime 2023-03-16
     */
    public function delFzxxm($request)
    {
        $jab_apply_did = $request['jab_apply_did'];
        $modules_id = $request['modules_id'];
        $result = JobApplyDetails::where('id',$jab_apply_did)->first();
        if(!$result){
            throw new \Exception('数据不存在');
        }
        $modules = json_decode($result->modules,true);
        unset($modules[array_search($modules_id,$modules)]);
        $data = array_values($modules);
        JobApplyDetails::where('id',$jab_apply_did)->update(['modules'=>json_encode($data)]);
        return $jab_apply_did;
    }

    /**
     * 获取教师申报数据列表
     * @author lxy
     * @datetime 2023-03-20
     */
    public function getApplyList($request)
    {
        $id = $request['id'];
        $limit = $request['limit'] ?? 10;
        $where[] = ['job_id','=',$id];

        $user_id = auth()->user()->id;
 
        !empty($request['search']['name'])     && $where[] = ['name','like','%'.$request['search']['name'].'%'];
        !empty($request['search']['subject'])     && $where[] = ['subject','like','%'.$request['search']['subject'].'%'];
        (isset($request['search']['status']) && $request['search']['status'] !== '')     && $where[] = ['status','=',$request['search']['status']];

        $result = JobApply::where($where)
                    ->with(['job_apply_check'=>function($q){
                        $q->where('status',1);
                    }])
                    ->orderBy('created_at','desc')
                    ->paginate($limit)
                    ->toArray();
                  
        //考评组长和成员才能审核
        $jobs = Job::where('id',$id)->first()->toArray();
        $a = !empty($jobs['leader_array']['name'])?count($jobs['leader_array']['name']):0;
        $b = !empty($jobs['members_array']['name'])?count($jobs['members_array']['name']):0;
        $zrs = $a+$b;
     
        if((!empty($jobs['leader_array']) && in_array($user_id,$jobs['leader_array']['value']))  || 
            (!empty($jobs['members_array']) && in_array($user_id,$jobs['members_array']['value']))
        ){
            $is_check = 1; //可以审核
        }else{
            $is_check = 0; //不能审核
        } 

        foreach($result['data'] as $k=>&$v){
            $v['is_check'] = $is_check;
            $v['check_sum'] = !empty($v['job_apply_check'])?count($v['job_apply_check']):0;
            $zs = 0;
            if(!empty($v['job_apply_check'])){
                $zs =  array_sum(array_column($v['job_apply_check'],'scores'));
            }
            $v['pj_score'] = $zs?round($zs/$v['check_sum'],1):0;
            $v['zrs'] = $zrs;
        }
        
        $result['limit'] = $limit;
  
        return $result;
    }

    /**
     * 考核小组成员审核提交
     * @author lxy
     * @datetime 2023-03-22
     */
    public function addJobApplyCheck($request)
    {
        $b_user_id = $request['user_id'];
        $p_user_id = auth()->user()->id;
        $p_user_name = auth()->user()->nickname;
        $job_apply_id = $request['job_apply_id'];
        $status = $request['status'];
        $scale_id = $request['scale_id'];

        try{
            DB::beginTransaction();
            if(!empty($request['score2s'])){      
                foreach($request['score2s'] as $k=>$v){
                    if($v){
                        $v =  json_decode($v,true);
                        JobApplyScores::updateOrCreate(
                            ['job_apply_id'=>$job_apply_id,'scale_id'=>$v['scale_id'],'type'=>2,'p_user_id'=>$p_user_id],
                            ['scores'=>$v['scores'],'b_user_id'=>$b_user_id,'p_user_name'=>$p_user_name]
                        );
                    }                      
                }
            }
      
            if(!empty($request['scores'])){
                foreach($request['scores'] as $k=>$v){
                    JobApplyScores::updateOrCreate(
                        ['job_apply_id'=>$job_apply_id,'scale_id'=>$k,'type'=>1,'p_user_id'=>$p_user_id],
                        ['scores'=>$v,'b_user_id'=>$b_user_id,'p_user_name'=>$p_user_name]
                    );
                }
            }

            if($status == 1){
                //全部打分之后才能提交
                $scale_detail = ScaleDetail::where('is_end',1)->where('scale_id',$scale_id)->count();
                $score_count = JobApplyScores::where('job_apply_id',$job_apply_id)->where('p_user_id',$p_user_id)->count();
                if($score_count < ($scale_detail+4)){
                    throw new \Exception('全部评分之后才能提交');
                }
            }
            
            //更新总分
            $z_scores = JobApplyScores::where('job_apply_id',$job_apply_id)->where('p_user_id',$p_user_id)->sum('scores');
          
            $jbc_status = JobApplyChecks::where('job_apply_id',$job_apply_id)->where('p_user_id',$p_user_id)->value('status');
            if($jbc_status == 1){
                $status = 1; 
            }
         
            JobApplyChecks::updateOrCreate(
                ['job_apply_id'=>$job_apply_id,'p_user_id'=>$p_user_id],
                ['p_user_name'=>$p_user_name,'scores'=>$z_scores,'status'=>$status]
            );

            //修改待办事项状态
            if($request['status'] == 1){
                Tasks::where('form_key','TEACHER_TASKS')->where('form_id',$job_apply_id)->where('c_user_id',$p_user_id)->update(['status'=>2]);
            }
            
                
            DB::commit(); 
            return [];                     
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 获取审核基础信息
     * @author lxy
     * @datetime 2023-03-23
     */
    public function getJobApplyCheckFirst($request)
    {
        $where = [];
        $job_apply_id = $request['job_apply_id'];
        if(!empty($request['p_user_id'])){
            $user_id = $request['p_user_id'];
        }else{
            $user_id = auth()->user()->id;
            $where[] = ['p_user_id','=',$user_id];
        }
        
        $where[] = ['job_apply_id','=',$job_apply_id];
        $where[] = ['type','=',1];
      
        $result = JobApply::where('id',$job_apply_id)->with(['job_apply_details'=>function($q) {
                    $q->where('type',1);
                },'jobs'])->first();
        $result = $result->toArray();
        $result['job_apply_details'] = array_column($result['job_apply_details'],null,'scale_id');

        //系统管管理员或考评组长能看全部考核成员的打分，考核小组成员只能看自己
        if(!is_checker()){
            if(!empty($result['jobs']['members_array']['all'])){
                $user_id = auth()->user()->id;
                foreach($result['jobs']['members_array']['all'] as $k=>$v){               
                    if($v['value'] == $user_id){
                        unset($result['jobs']['members_array']['all']);
                        $result['jobs']['members_array']['all'][] = $v;
                        $result['jobs']['leader_array']['all'] = [];
                        break;
                    }
                }
            }
        }
     
        $job_apply_scores = JobApplyScores::where($where)->get()->toArray();
        if($job_apply_scores){
            $job_apply_scores = array_column($job_apply_scores,null,'scale_id');
            $result['job_apply_details'][1]['scores'] = !empty($job_apply_scores[1])?$job_apply_scores[1]['scores']:$result['job_apply_details'][1]['scores'];
            $result['job_apply_details'][2]['scores'] = !empty($job_apply_scores[2])?$job_apply_scores[2]['scores']:$result['job_apply_details'][2]['scores'];
            $result['job_apply_details'][3]['scores'] = !empty($job_apply_scores[3])?$job_apply_scores[3]['scores']:$result['job_apply_details'][3]['scores'];
            $result['job_apply_details'][4]['scores'] = !empty($job_apply_scores[4])?$job_apply_scores[4]['scores']:$result['job_apply_details'][4]['scores'];
        }       
        
        return $result;
    }

    /**
     * 获取发展性项目审核列表
     * @author lxy
     * @datetime 2023-03-23
     */
    public function getJobScaleCheckList($request)
    {
        $scale_index = $request['scale_index'];
        $scale_id = $request['scale_id'];
        $job_apply_id = $request['job_apply_id'];
        if(!empty($request['p_user_id'])){
            $p_user_id = $request['p_user_id'];
        }else{
            $p_user_id = auth()->user()->id;
        }
        if($scale_index == 2){
            //科教研 特殊处理
            $result = ScaleDetail::whereIn('scale_index',[2,3])->where('is_end',1)->where('scale_id',$scale_id)
                ->with(['jobApplyDetails'=>function($q) use($job_apply_id){
                    $q->where('job_apply_id',$job_apply_id)->where('type',2);
                },'jobApplyScores'=>function($q) use($job_apply_id,$p_user_id){
                    $q->where('job_apply_id',$job_apply_id)->where('p_user_id',$p_user_id)->where('type',2)->select('job_apply_id','scale_id','type','p_user_id','scores');
                }])->get()->toArray();
             
            $data = [];
            foreach($result as $k=>$v){
                $data[$v['scale_index']][] = $v;
            }
            return $data;
        }else if($scale_index == 5){
            //公开教学 特殊处理
            $result = ScaleDetail::whereIn('scale_index',[5,10])->where('is_end',1)->where('scale_id',$scale_id)
                ->with(['jobApplyDetails'=>function($q) use($job_apply_id){
                    $q->where('job_apply_id',$job_apply_id)->where('type',2);
                },'jobApplyScores'=>function($q) use($job_apply_id,$p_user_id){
                    $q->where('job_apply_id',$job_apply_id)->where('p_user_id',$p_user_id)->where('type',2)->select('job_apply_id','scale_id','type','p_user_id','scores');
                }])->get()->toArray();
             
            $data = [];
            foreach($result as $k=>$v){
                $data[$v['scale_index']][] = $v;
            }
            return $data;
        }else{
            $result = ScaleDetail::where('scale_index',$scale_index)->where('is_end',1)->where('scale_id',$scale_id)
            ->with(['jobApplyDetails'=>function($q) use($job_apply_id){
                $q->where('job_apply_id',$job_apply_id)->where('type',2);
            },'jobApplyScores'=>function($q) use($job_apply_id,$p_user_id){
                $q->where('job_apply_id',$job_apply_id)->where('p_user_id',$p_user_id)->where('type',2)->select('job_apply_id','scale_id','type','p_user_id','scores');
            }])->get()->toArray();
        }
        
        return $result;
    }

    /**
     * 获取最终认定申报理由
     * @author lxy
     * @datetime 2023-03-23
     */
    public function getFinalJobApplyList($request)
    {
        $where = [];
        $job_apply_id = $request['job_apply_id'];   
        $where[] = ['job_apply_id','=',$job_apply_id];
        $where[] = ['type','=',1];

        //打分人数
        $check_menber = JobApplyChecks::where('job_apply_id',$job_apply_id)->where('status',1)->pluck('p_user_id')->toArray();
        
        $check_sum = count($check_menber);
        $result = JobApply::where('id',$job_apply_id)->with(['job_apply_details'=>function($q) {
                    $q->where('type',1);
                }])->first();
        $result = $result->toArray();
        $result['job_apply_details'] = array_column($result['job_apply_details'],null,'scale_id');

        if(!$check_menber){
            $job_apply_scores = [];
        }else{
            $job_apply_scores = JobApplyScores::where($where)->whereIn('p_user_id',$check_menber)->get()->toArray();
        }
        
        
        if(!empty($job_apply_scores) && $check_sum){
            $data = [];
            foreach($job_apply_scores as $k =>$v){     
                $data[$v['scale_id']][] = $v['scores'];
            }
            
            foreach($data as $k=>$v){
                $data[$k] = round(array_sum($v)/$check_sum,1);  //四舍五入保留一位小数
            }
         
            $job_apply_scores = $data;
            $result['job_apply_details'][1]['scores'] = !empty($job_apply_scores[1])?$job_apply_scores[1]:$result['job_apply_details'][1]['scores'];
            $result['job_apply_details'][2]['scores'] = !empty($job_apply_scores[2])?$job_apply_scores[2]:$result['job_apply_details'][2]['scores'];
            $result['job_apply_details'][3]['scores'] = !empty($job_apply_scores[3])?$job_apply_scores[3]:$result['job_apply_details'][3]['scores'];
            $result['job_apply_details'][4]['scores'] = !empty($job_apply_scores[4])?$job_apply_scores[4]:$result['job_apply_details'][4]['scores'];
        }       
        
        return $result;
    }

    /**
     * 获取最终认定发展性项目
     * @author lxy
     * @datetime 2023-03-24
     */
    public function getFinatJobScaleList($request)
    {
        $scale_index = $request['scale_index'];
        $scale_id = $request['scale_id'];
        $job_apply_id = $request['job_apply_id'];
        

        //打分人数
        $check_menber = JobApplyChecks::where('job_apply_id',$job_apply_id)->where('status',1)->pluck('p_user_id')->toArray();
        $check_sum = count($check_menber);
        if(!$check_menber){
            $data = [];
        }else{
            $job_apply_scores = JobApplyScores::where('job_apply_id',$job_apply_id)->where('type',2)->whereIn('p_user_id',$check_menber)->get()->toArray();
            foreach($job_apply_scores as $k =>$v){     
                $data[$v['scale_id']][] = $v['scores'];
            }
       
            foreach($data as $k=>$v){
                $data[$k] = round(array_sum($v)/$check_sum,1);  //四舍五入保留一位小数
            }
        }

        if($scale_index == 2){
            //科教研 特殊处理
            $result = ScaleDetail::whereIn('scale_index',[2,3])->where('is_end',1)->where('scale_id',$scale_id)
                ->with(['jobApplyDetails'=>function($q) use($job_apply_id){
                    $q->where('job_apply_id',$job_apply_id)->where('type',2);
                }])->get()->toArray();        
            foreach($result as $k=>&$v){
                $v['job_apply_scores']['scores'] = !empty($data[$v['id']])?$data[$v['id']]:0;
            }  
            $res = [];
            foreach($result as $k=>$v){
                $res[$v['scale_index']][] = $v;
            }
            return $res;
        }else if($scale_index == 5){
            //公开教学 特殊处理
            $result = ScaleDetail::whereIn('scale_index',[5,10])->where('is_end',1)->where('scale_id',$scale_id)
            ->with(['jobApplyDetails'=>function($q) use($job_apply_id){
                $q->where('job_apply_id',$job_apply_id)->where('type',2);
            }])->get()->toArray();        
            foreach($result as $k=>&$v){
            $v['job_apply_scores']['scores'] = !empty($data[$v['id']])?$data[$v['id']]:0;
            }  
            $res = [];
            foreach($result as $k=>$v){
            $res[$v['scale_index']][] = $v;
            }
            return $res;
        }else{
            $result = ScaleDetail::where('scale_index',$scale_index)->where('is_end',1)->where('scale_id',$scale_id)
            ->with(['jobApplyDetails'=>function($q) use($job_apply_id){
                $q->where('job_apply_id',$job_apply_id)->where('type',2);
            }])->get()->toArray();
            foreach($result as $k=>&$v){
                $v['job_apply_scores']['scores'] = !empty($data[$v['id']])?$data[$v['id']]:0;
            }
        }
        
        return $result;
    }

     /**
     * 获取考核小组成员申报理由分
     * @author lxy
     * @datetime 2023-03-24
     */
    public function getJobApplyUserCheck($request)
    {
        $where = [];
        $job_apply_id = $request['job_apply_id'];
        $user_id = $request['p_user_id'];
        $where[] = ['p_user_id','=',$user_id];
        $where[] = ['job_apply_id','=',$job_apply_id];
        $where[] = ['type','=',1];

        $result = JobApply::where('id',$job_apply_id)->with(['job_apply_details'=>function($q) {
                    $q->where('type',1);
                },'jobs'])->first();
        $result = $result->toArray();
        $result['job_apply_details'] = array_column($result['job_apply_details'],null,'scale_id');

        $job_apply_scores = JobApplyScores::where($where)->get()->toArray();
        if($job_apply_scores){
            $job_apply_scores = array_column($job_apply_scores,null,'scale_id');
            $result['job_apply_details'][1]['scores'] = !empty($job_apply_scores[1])?$job_apply_scores[1]['scores']:$result['job_apply_details'][1]['scores'];
            $result['job_apply_details'][2]['scores'] = !empty($job_apply_scores[2])?$job_apply_scores[2]['scores']:$result['job_apply_details'][2]['scores'];
            $result['job_apply_details'][3]['scores'] = !empty($job_apply_scores[3])?$job_apply_scores[3]['scores']:$result['job_apply_details'][3]['scores'];
            $result['job_apply_details'][4]['scores'] = !empty($job_apply_scores[4])?$job_apply_scores[4]['scores']:$result['job_apply_details'][4]['scores'];
        }       
        
        return $result;
    }

    /**
     * 获取个人考核总分
     * @author lxy
     * @datetime 2023-03-24
     */
    public function getUserCheckScores($request)
    {
        $job_apply_id = $request['job_apply_id'];
        $user_id = $request['p_user_id'];
        $result = JobApplyChecks::where('job_apply_id',$job_apply_id)->where('p_user_id',$user_id)->where('status',1)->value('scores');
        if(!$result){
            $result = 0;
        }
        return $result;
    }

    /**
     * 删除
     * @author lxy
     * @datetime 2023-03-24
     */
    public function delJobApply($request)
    {
        $id = $request['id'];
       // Tasks::where('form_key','TEACHER_TASKS')->where('form_id',$id)->where('status',1)->delete();
        $retult = Job::where('id',$id)->delete();

        return $retult;
    }

    /**
     * 导出
     * @author lxy
     * @datetime 2023-03-27
     */
    public function exportJobApply($request)
    {
        $id = $request['id'];
        $where[] = ['job_id','=',$id];
 
        !empty($request['search']['name'])     && $where[] = ['name','like','%'.$request['search']['name'].'%'];
        !empty($request['search']['subject'])     && $where[] = ['subject','like','%'.$request['search']['subject'].'%'];
        (isset($request['search']['status']) && $request['search']['status'] !== '')     && $where[] = ['status','=',$request['search']['status']];

        $result = JobApply::where($where)
                    ->with(['job_apply_check'=>function($q){
                        $q->where('status',1);
                    }])
                    ->orderBy('created_at','desc')
                    ->get()
                    ->toArray();

                    //考评组长和成员才能审核
        $jobs = Job::where('id',$id)->first()->toArray();
        $a = !empty($jobs['leader_array']['name'])?count($jobs['leader_array']['name']):0;
        $b = !empty($jobs['members_array']['name'])?count($jobs['members_array']['name']):0;
        $zrs = $a+$b;   
                  
        $field_name = ['序号','教师姓名','任教学科','原岗位','申报岗位','分数','审核进度','申报时间'];  
        $data = [];
        foreach($result as $k=>&$v){
            $v['check_sum'] = !empty($v['job_apply_check'])?count($v['job_apply_check']):0;
            $zs = 0;
            if(!empty($v['job_apply_check'])){
                $zs =  array_sum(array_column($v['job_apply_check'],'scores'));
            }
            $data[$k]['key'] = ++$k;
            $data[$k]['name'] = $v['name'];
            $data[$k]['subject'] = $v['subject'];
            $data[$k]['old_level_name'] = $v['old_level_name'];
            $data[$k]['apply_level_name'] = $v['apply_level_name'];
            $data[$k]['score'] = $zs?round($zs/$v['check_sum'],1):0;
            $data[$k]['shjd'] = $v['check_sum'].'/'.$zrs;
            $data[$k]['created_at'] = $v['created_at'];
        }
        array_unshift($data,$field_name);

        $file_name = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($data), $file_name, 'excel');
        return [
            'file_name' => $file_name,
        ];
    }

    //岗位级别
    private function level($key){
        $level = [
            '1' => '一级',
            '2' => '二级',
            '3' => '三级',
            '4' => '四级',
            '5' => '五级',
            '6' => '六级',
            '7' => '七级',
            '8' => '八级',
            '9' => '九级',
            '10' => '十级',
            '11' => '十一级',
            '12' => '十二级',
            '13' => '十三级',
        ];
        return !empty($level[$key])?$level[$key]:'';
    }

    //学历
    private function education($key){
        $data = [
            '2' => 7,
            '3' => 5,
        ];
        return !empty($data[$key])?$data[$key]:'';
    }

    //教龄
    private function teaching_age($key)
    {
        if($key>=0 && $key<=2){
            return 1;
        }else if($key>=3 && $key<=4){
            return 2;
        }else if($key>=5 && $key<=6){
            return 3;
        }else if($key>=7 && $key<=8){
            return 4;
        }else if($key>=9 && $key<=10){
            return 5;
        }else if($key>=11 && $key<=12){
            return 6;
        }else if($key>=13 && $key<=14){
            return 7;
        }else if($key>=15 && $key<=16){
            return 8;
        }else if($key>=17 && $key<=18){
            return 9;
        }else if($key>=19 && $key<=20){
            return 10;
        }else if($key>=21 && $key<=22){
            return 11;
        }else if($key>=23 && $key<=24){
            return 12;
        }else if($key>=25 && $key<=26){
            return 13;
        }else if($key>=27 && $key<=28){
            return 14;
        }else if($key>=29){
            return 15;
        }
    }

     
    
    /**
     * @Description: 通过条件获取基础信息
     * @Author: kzj
     * @datetime: 2023-03-30
     */
    public function getJobCompetitionInfo($request)
    {
        if(empty($request['data_version_id'])) {
            throw new \Exception('参数缺失！');
        }

        if(!$request['user_id']) {
            $user = Auth::user();
            $userId = $user->id;
        } else {
            $userId = $request['user_id'];
        }
        
        $result = JobApply::where('user_id', $userId)
            ->where('data_version_id', $request['data_version_id'])
            ->with("jobs:id,scale_id")
            ->first();

        return $result;
    }

}